package com.atguigu.controller;

import com.atguigu.controller.base.ModelBaseServlet;
import com.atguigu.pojo.*;
import com.atguigu.service.BookService;
import com.atguigu.service.impl.BookServiceImpl;
import com.atguigu.utils.JSONUtils;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

/**
 * @Author luoyin
 * @Date 16:06 2022/7/21
 * @Description 描述
 **/
@WebServlet("/cart")
public class CartClientController extends ModelBaseServlet {
    //查询购物车数量
    public void selectCart(HttpServletRequest request, HttpServletResponse response){
        Cart cart = (Cart) request.getSession().getAttribute(BookstoreConstant.SESSION_KEY_CART);
        ResultVO<Cart> resultVO = new ResultVO<>(true,"查询购物车成功",cart);
        try {
            JSONUtils.object2JsonStrAndresponse(response,resultVO);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //加入购物车
    public void add2CartItem(HttpServletRequest request, HttpServletResponse response){

        Integer bookId = Integer.valueOf(request.getParameter("bookId"));
        Cart cart = (Cart) request.getSession().getAttribute("cart");
        BookService bookService = new BookServiceImpl();
        ResultVO<Cart> resultVO = null;
        try {
            Book book = bookService.selectById(bookId);
            if (cart == null){
                cart = new Cart();
            }
            cart.addBook2CartItem(book);
            request.getSession().setAttribute("cart",cart);
            resultVO=new ResultVO<>(true,"加入购物车成功",null);
        } catch (Exception e) {
            e.printStackTrace();
            resultVO=new ResultVO<>(false,"加入购物车失败",null);
        }
        try {
            JSONUtils.object2JsonStrAndresponse(response,resultVO);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
